package com.hermit.qmst.UI.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.BusinessActivity;
import com.hermit.qmst.UI.activity.CurrencyActivity;
import com.hermit.qmst.UI.activity.OfficialActivity;
import com.hermit.qmst.UI.activity.OpenUrlActivity;
import com.hermit.qmst.adapter.FindAdapter;
import com.hermit.qmst.mode.FindListViewInfo;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by hermithermit on 15/3/31.
 */


public class FindFragment extends Fragment {

    private static final String TAG = "发现：FindFragment_";
    private View mView;
    private TextView mTitle;
    private ListView lvProduct_list;
    private FindAdapter adapter;
    //    private Class findClass[] = {BusinessActivity.class, BusinessActivity.class};
//    •type的对应值 1->消息 2->官方动态 4->企业动态 8->合作加盟 16->咨询电话 32->通用  64->专线消息   128->企业链接
    private Map<Integer, Class> findClass = new HashMap<Integer, Class>();
    private String number = "";
    private String loadUrl = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        findClass.put(1, BusinessActivity.class);  //消息
        findClass.put(2, OfficialActivity.class);  //官方动态
        findClass.put(4, OfficialActivity.class);  //企业动态
        findClass.put(8, BusinessActivity.class);  //合作加盟
        findClass.put(16, BusinessActivity.class); //咨询电话
        findClass.put(32, CurrencyActivity.class); //通用
        findClass.put(64, BusinessActivity.class); //专线消息
        findClass.put(128, OpenUrlActivity.class); //企业链接
        getPhone();
        getLoadUrl();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_find, null);
            mTitle = (TextView) mView.findViewById(R.id.tv_title);
            lvProduct_list = (ListView) mView.findViewById(R.id.lv_product_list);
            mTitle.setText("发现");
            adapter = new FindAdapter(getActivity());
            lvProduct_list.setAdapter(adapter);
            onClickItem();
            initDate();
        } else {
            ViewGroup vp = (ViewGroup) mView.getRootView();
            vp.removeView(mView);

        }

        return mView;
    }

    private void initDate() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        String url = Common.submitDiscovery() + "?agentId=" + Common.mAgentId;
        Log.i(TAG + "url", url, true);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject object) {
                Log.i(TAG + "onResponse", object.toString(), true);
                if (object != null && object.length() > 0) {
                    try {
                        if (object.getBoolean("state")) {
                            JSONArray jsonArray = object.getJSONArray("array");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject ob = jsonArray.getJSONObject(i);
                                FindListViewInfo info = new FindListViewInfo();
                                info.setTitle(ob.getString("title"));
                                info.setLogo(ob.getString("logo"));
                                info.setSort(ob.getInt("sort"));
                                info.setType(ob.getInt("type"));
                                info.setDescrible(ob.getString("describle"));
                                adapter.data.add(info);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "json格式解析错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        requestQueue.add(request);
    }

    private void onClickItem() {
        lvProduct_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int type = adapter.data.get(position).getType();
                if (type == 16) {
                    //咨询电话
                    if (number.length() > 0) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
                        startActivity(intent);
                    } else {
                        Toast.makeText(getActivity(), "暂无咨询热线号码", Toast.LENGTH_SHORT).show();
                    }

                } else if (type == 128) {
                    //  128->企业链接
                    if (loadUrl.length() > 0) {
                        Intent intent = new Intent(getActivity(), OpenUrlActivity.class);
                        intent.putExtra("title", "企业链接");
                        intent.putExtra("url", loadUrl);
                        //intent.putExtra("url", mImageToUrlList.get(mPosition));
                        getActivity().startActivity(intent);
                    }

                } else {
                    Intent intent = new Intent(getActivity(), findClass.get(type));
                    intent.putExtra("title", adapter.data.get(position).getTitle());
                    intent.putExtra("type", type);
                    getActivity().startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void getPhone() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        String url = Common.mUrl + "szdh/discovery/consultTel.php?agentId=" + Common.mAgentId;
        Log.i(TAG + "getPhone_url", url, true);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject object) {
                Log.i(TAG + "getPhone_request", object.toString(), true);
                try {
                    number = object.getString("phone");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        requestQueue.add(request);
        Log.i(TAG, url, true);
    }

    private void getLoadUrl() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        String url = Common.mUrl + "szdh/discovery/officialUrl.php?agenId=" + Common.mAgentId;
        Log.i(TAG + "getLoadUrl_url", url, true);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject object) {
                Log.i(TAG + "getLoadUrl_request", object.toString(), true);
                try {
                    if (object.getBoolean("state")) {
                        loadUrl = object.getString("url");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        requestQueue.add(request);
        Log.i(TAG, url, true);
    }
}
